<?php

namespace App\Http\Controllers\Admin;

use App\Model\Admin;
use App\Model\Role;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Admin\IndexController;
use Illuminate\Support\Facades\DB;

class AdminController extends Controller
{
    /**
     * 用户列表页
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        // 获取get请求传递的参数
//        $input = $request->all();
        // 查询用户数据
        $userlist = Admin::orderBy('id','asc')
            ->where(function($query) use($request){
                $username = $request->input('username');
                if(!empty($username)){
                    $query->where('username','like','%'. $username .'%');
                }
            })
            ->paginate($request->input('num') ? $request->input('num') : 10);

        return view('admin.admin.list',compact('userlist','request'));
    }

    /**
     * 返回一个用户添加页
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.admin.add');
    }

    /**
     *  执行添加操作
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // 1.获取用户添加的数据  username nickname pass repass
        $input = $request->all();

        // 生成密码盐
        $salt = IndexController::build_ranstr();

        // 进行加密
        $password = md5($input['pass'].$salt);

        $username = Admin::where('username',$input['username'])->first();

        if($username){
            $data = [
                'code'=> 0,
                'message'=>'该管理员已经存在'
            ];
            return $data;
        }

        // 封装插入数据库的数组
        $data = [
            'username' => $input['username'],
            'nickname' => $input['nickname'],
            'password' => $password,
            'salt' => $salt,
            'state' => '1',
        ];

        // 验证
        $result = Admin::create($data);

        if($result === FALSE){
            $data = [
                'code'=> 0,
                'message'=>'添加失败'
            ];
        }else{
            $data = [
                'code'=> 1,
                'message'=>'添加成功'
            ];
        }
        return $data;
    }

    /**
     * 显示一条用户数据
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * 返回修改用户页
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $user = Admin::find($id);

        // 获取所有的角色列表
        $roles = Role::get();

        // 获取当前管理人的有哪些角色
        $own_roles = $user->admin_role;

        $own_rols = [];
        // 如果没有数据给一个空数组
        if(empty($own_roles)){
            $own_rols = [];
        }else{
            foreach ($own_roles as $v){
                $own_rols[] = $v->id;
            }
        }

        return view('admin.admin.edit',compact('user','roles','own_rols'));
    }

    /**
     * 执行修改操作
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        // 开启事务
        DB::beginTransaction();

        try {
            // 查询
            $user = Admin::find($id);

            $input = $request->all();

            // 获取修改的数据
            $username = $request->input('username');
            $nickname = $request->input('nickname');
            $state = $request->input('state');

            $user->username = $username;
            $user->nickname = $nickname;
            $user->state = $state;

            $adminStatus = $user->update();
            // admin表修改
            if ($adminStatus === FALSE) {
                throw new \Exception("admin表修改失败");
            }

            // 先删除管理角色表
            $adminRoleStatus = DB::table('admin_role')->where(['admin_id' => $id])->delete();

            if ($adminRoleStatus === FALSE) {
                throw new \Exception("管理角色表删除失败");
            }

            // 在追加相对应的角色
            if(!empty($input['role_id'])){
                foreach ($input['role_id'] as $v){
                    $admin_RoleStatus = DB::table('admin_role')->insert(['role_id'=>$v,'admin_id'=>$input['admin_id']]);

                    if ($admin_RoleStatus === FALSE) {
                        throw new \Exception("管理角色表添加失败");
                    }
                }
            }

            DB::commit();

            $data = [
                'code'=> 1,
                'message'=>'修改成功'
            ];

            return $data;

        }catch (\Exception $Error){
            DB::rollBack();
            $data = [
                'code'=> 0,
                'message'=> '修改成功'
            ];

            return $data;

        }

    }

    /**
     * 执行删除操作
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $user = Admin::find($id);

        $result = $user->delete();

        if($result === FALSE){
            $data = [
                'code'=> 0,
                'message'=>'删除失败'
            ];
        }else{
            $data = [
                'code'=> 1,
                'message'=>'删除成功'
            ];
        }

        return $data;
    }

    // 删除选中id
    public function delAll(Request $request)
    {
        $ids = $request->input('ids');

        $result = Admin::destroy($ids);

        if($result === FALSE){
            $data = [
                'code'=> 0,
                'message'=>'删除失败'
            ];
        }else{
            $data = [
                'code'=> 1,
                'message'=>'删除成功'
            ];
        }

        return $data;

    }

}
